<?php

namespace Home\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;


class LichdayTable extends AbstractTableGateway {

    protected $table = 'lichday';

    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new Lichday());

        $this->initialize();
    }

    public function fetchAll(Select $select = null) {
        if (null === $select)
            $select = new Select();
        $select->from($this->table,array('*'))
				->join(
					'lop',
					'lop.id = lichday.lop',
					array('tenlop'))
				->join(
					'thu',
					'thu.id = lichday.thu',
					array('tenthu'))
				->join(
					'tiet',
					'tiet.id = lichday.tiet',
					array('tentiet'))
				->join(
					'giaovien',
					'giaovien.id = lichday.giaovien',
					array('tengv','gioitinh'));
        $resultSet = $this->selectWith($select);
        $resultSet->buffer();
        return $resultSet;
    }

    public function getLichday($id) {
        $id = (int) $id;
        $rowset = $this->select(array('id' => $id));
        $row = $rowset->current(); 
        return $row;
    }

    public function saveLichday(Lichday $lichday) {
		
			
		
        

        $id = (int) $lichday->id;
        if ($id == 0) {
			$data = array(
				'thu' => $lichday->thu,
				'giaovien' => $lichday->giaovien,
				'tiet' => $lichday->tiet,
				'lop' => $lichday->lop,
				'buoi' => $lichday->buoi,
			);
            	
                $this->insert($data);
            
        } else {
			
			$data = array(
				'thu' => $lichday->thu,
				'giaovien' => $lichday->giaovien,
				'tiet' => $lichday->tiet,
				'lop' => $lichday->lop,
				'buoi' => $lichday->buoi,
			);
            if ($this->getLichday($id)) {
				
					$this->update($data, array('id' => $id));
				
            } else {
                throw new \Exception('Không tồn tại');
            }
        }
    }

    public function deleteLichday($id) {
        $this->delete(array('id' => $id));
    }
	
	//kiem tra ton tai
	public function check_exists($lop,$thu,$giaovien,$tiet,$id)
	{
		//$rowset = $this->select(array('title' => $title));
        //$row = $rowset->current();
		$resultSet = $this->select(array('lop = "'.$lop.'"','thu = "'.$thu.'"','tiet = "'.$tiet.'"','giaovien = "'.$giaovien.'"', 'id != "'.$id.'"'));
    	$row = $resultSet->current();
        return $row;
		
	}
	


}
